home *** CD-ROM | disk | FTP | other *** search
/ Complete Internet Archive / Complete Internet Archive.iso / Perl / cgi-lib.pl.txt next >
Text File  |  1997-01-26  |  15KB  |  460 lines

  1.  
  2.  
  3. # Perl Routines to Manipulate CGI input
  4. # S.E.Brenner@bioc.cam.ac.uk
  5. # $Id: cgi-lib.pl,v 2.14 1996/10/20 12:41:02 brenner Exp $
  6. #
  7. # Copyright (c) 1996 Steven E. Brenner  
  8. # Unpublished work.
  9. # Permission granted to use and modify this library so long as the
  10. # copyright above is maintained, modifications are documented, and
  11. # credit is given for any use of the library.
  12. #
  13. # Thanks are due to many people for reporting bugs and suggestions
  14. # especially Meng Weng Wong, Maki Watanabe, Bo Frese Rasmussen,
  15. # Andrew Dalke, Mark-Jason Dominus, Dave Dittrich, Jason Mathews
  16.  
  17. # For more information, see:
  18. #     http://www.bio.cam.ac.uk/cgi-lib/
  19.  
  20. $cgi_lib'version = sprintf("%d.%02d", q$Revision: 2.14 $ =~ /(\d+)\.(\d+)/);
  21.  
  22.  
  23. # Parameters affecting cgi-lib behavior
  24. # User-configurable parameters affecting file upload.
  25. $cgi_lib'maxdata    = 131072;    # maximum bytes to accept via POST - 2^17
  26. $cgi_lib'writefiles =      0;    # directory to which to write files, or
  27.                                  # 0 if files should not be written
  28. $cgi_lib'filepre    = "cgi-lib"; # Prefix of file names, in directory above
  29.  
  30. # Do not change the following parameters unless you have special reasons
  31. $cgi_lib'bufsize  =  8192;    # default buffer size when reading multipart
  32. $cgi_lib'maxbound =   100;    # maximum boundary length to be encounterd
  33. $cgi_lib'headerout =    0;    # indicates whether the header has been printed
  34.  
  35.  
  36. # ReadParse
  37. # Reads in GET or POST data, converts it to unescaped text, and puts
  38. # key/value pairs in %in, using "\0" to separate multiple selections
  39.  
  40. # Returns >0 if there was input, 0 if there was no input 
  41. # undef indicates some failure.
  42.  
  43. # Now that cgi scripts can be put in the normal file space, it is useful
  44. # to combine both the form and the script in one place.  If no parameters
  45. # are given (i.e., ReadParse returns FALSE), then a form could be output.
  46.  
  47. # If a reference to a hash is given, then the data will be stored in that
  48. # hash, but the data from $in and @in will become inaccessable.
  49. # If a variable-glob (e.g., *cgi_input) is the first parameter to ReadParse,
  50. # information is stored there, rather than in $in, @in, and %in.
  51. # Second, third, and fourth parameters fill associative arrays analagous to
  52. # %in with data relevant to file uploads. 
  53.  
  54. # If no method is given, the script will process both command-line arguments
  55. # of the form: name=value and any text that is in $ENV{'QUERY_STRING'}
  56. # This is intended to aid debugging and may be changed in future releases
  57.  
  58. sub ReadParse {
  59.   local (*in) = shift if @_;    # CGI input
  60.   local (*incfn,                # Client's filename (may not be provided)
  61.      *inct,                 # Client's content-type (may not be provided)
  62.      *insfn) = @_;          # Server's filename (for spooled files)
  63.   local ($len, $type, $meth, $errflag, $cmdflag, $perlwarn, $got);
  64.     
  65.   # Disable warnings as this code deliberately uses local and environment
  66.   # variables which are preset to undef (i.e., not explicitly initialized)
  67.   $perlwarn = $^W;
  68.   $^W = 0;
  69.  
  70.   binmode(STDIN);   # we need these for DOS-based systems
  71.   binmode(STDOUT);  # and they shouldn't hurt anything else 
  72.   binmode(STDERR);
  73.     
  74.   # Get several useful env variables
  75.   $type = $ENV{'CONTENT_TYPE'};
  76.   $len  = $ENV{'CONTENT_LENGTH'};
  77.   $meth = $ENV{'REQUEST_METHOD'};
  78.   
  79.   if ($len > $cgi_lib'maxdata) { #'
  80.       &CgiDie("cgi-lib.pl: Request to receive too much data: $len bytes\n");
  81.   }
  82.   
  83.   if (!defined $meth || $meth eq '' || $meth eq 'GET' || 
  84.       $type eq 'application/x-www-form-urlencoded') {
  85.     local ($key, $val, $i);
  86.     
  87.     # Read in text
  88.     if (!defined $meth || $meth eq '') {
  89.       $in = $ENV{'QUERY_STRING'};
  90.       $cmdflag = 1;  # also use command-line options
  91.     } elsif($meth eq 'GET' || $meth eq 'HEAD') {
  92.       $in = $ENV{'QUERY_STRING'};
  93.     } elsif ($meth eq 'POST') {
  94.         if (($got = read(STDIN, $in, $len) != $len))
  95.       {$errflag="Short Read: wanted $len, got $got\n";};
  96.     } else {
  97.       &CgiDie("cgi-lib.pl: Unknown request method: $meth\n");
  98.     }
  99.  
  100.     @in = split(/[&;]/,$in); 
  101.     push(@in, @ARGV) if $cmdflag; # add command-line parameters
  102.  
  103.     foreach $i (0 .. $#in) {
  104.       # Convert plus to space
  105.       $in[$i] =~ s/\+/ /g;
  106.  
  107.       # Split into key and value.  
  108.       ($key, $val) = split(/=/,$in[$i],2); # splits on the first =.
  109.  
  110.       # Convert %XX from hex numbers to alphanumeric
  111.       $key =~ s/%([A-Fa-f0-9]{2})/pack("c",hex($1))/ge;
  112.       $val =~ s/%([A-Fa-f0-9]{2})/pack("c",hex($1))/ge;
  113.  
  114.       # Associate key and value
  115.       $in{$key} .= "\0" if (defined($in{$key})); # \0 is the multiple separator
  116.       $in{$key} .= $val;
  117.     }
  118.  
  119.   } elsif ($ENV{'CONTENT_TYPE'} =~ m#^multipart/form-data#) {
  120.     # for efficiency, compile multipart code only if needed
  121. $errflag = !(eval <<'END_MULTIPART');
  122.  
  123.     local ($buf, $boundary, $head, @heads, $cd, $ct, $fname, $ctype, $blen);
  124.     local ($bpos, $lpos, $left, $amt, $fn, $ser);
  125.     local ($bufsize, $maxbound, $writefiles) = 
  126.       ($cgi_lib'bufsize, $cgi_lib'maxbound, $cgi_lib'writefiles);
  127.  
  128.  
  129.     # The following lines exist solely to eliminate spurious warning messages
  130.     $buf = ''; 
  131.  
  132.     ($boundary) = $type =~ /boundary="([^"]+)"/; #";   # find boundary
  133.     ($boundary) = $type =~ /boundary=(\S+)/ unless $boundary;
  134.     &CgiDie ("Boundary not provided: probably a bug in your server") 
  135.       unless $boundary;
  136.     $boundary =  "--" . $boundary;
  137.     $blen = length ($boundary);
  138.  
  139.     if ($ENV{'REQUEST_METHOD'} ne 'POST') {
  140.       &CgiDie("Invalid request method for  multipart/form-data: $meth\n");
  141.     }
  142.  
  143.     if ($writefiles) {
  144.       local($me);
  145.       stat ($writefiles);
  146.       $writefiles = "/tmp" unless  -d _ && -r _ && -w _;
  147.       # ($me) = $0 =~ m#([^/]*)$#;
  148.       $writefiles .= "/$cgi_lib'filepre"; 
  149.     }
  150.  
  151.     # read in the data and split into parts:
  152.     # put headers in @in and data in %in
  153.     # General algorithm:
  154.     #   There are two dividers: the border and the '\r\n\r\n' between
  155.     # header and body.  Iterate between searching for these
  156.     #   Retain a buffer of size(bufsize+maxbound); the latter part is
  157.     # to ensure that dividers don't get lost by wrapping between two bufs
  158.     #   Look for a divider in the current batch.  If not found, then
  159.     # save all of bufsize, move the maxbound extra buffer to the front of
  160.     # the buffer, and read in a new bufsize bytes.  If a divider is found,
  161.     # save everything up to the divider.  Then empty the buffer of everything
  162.     # up to the end of the divider.  Refill buffer to bufsize+maxbound
  163.     #   Note slightly odd organization.  Code before BODY: really goes with
  164.     # code following HEAD:, but is put first to 'pre-fill' buffers.  BODY:
  165.     # is placed before HEAD: because we first need to discard any 'preface,'
  166.     # which would be analagous to a body without a preceeding head.
  167.  
  168.     $left = $len;
  169.    PART: # find each part of the multi-part while reading data
  170.     while (1) {
  171.       die $@ if $errflag;
  172.  
  173.       $amt = ($left > $bufsize+$maxbound-length($buf) 
  174.           ?  $bufsize+$maxbound-length($buf): $left);
  175.       $errflag = (($got = read(STDIN, $buf, $amt, length($buf))) != $amt);
  176.       die "Short Read: wanted $amt, got $got\n" if $errflag;
  177.       $left -= $amt;
  178.  
  179.       $in{$name} .= "\0" if defined $in{$name}; 
  180.       $in{$name} .= $fn if $fn;
  181.  
  182.       $name=~/([-\w]+)/;  # This allows $insfn{$name} to be untainted
  183.       if (defined $1) {
  184.         $insfn{$1} .= "\0" if defined $insfn{$1}; 
  185.         $insfn{$1} .= $fn if $fn;
  186.       }
  187.  
  188.      BODY: 
  189.       while (($bpos = index($buf, $boundary)) == -1) {
  190.         die $@ if $errflag;
  191.         if ($name) {  # if no $name, then it's the prologue -- discard
  192.           if ($fn) { print FILE substr($buf, 0, $bufsize); }
  193.           else     { $in{$name} .= substr($buf, 0, $bufsize); }
  194.         }
  195.         $buf = substr($buf, $bufsize);
  196.         $amt = ($left > $bufsize ? $bufsize : $left); #$maxbound==length($buf);
  197.         $errflag = (($got = read(STDIN, $buf, $amt, $maxbound)) != $amt);  
  198.     die "Short Read: wanted $amt, got $got\n" if $errflag;
  199.         $left -= $amt;
  200.       }
  201.       if (defined $name) {  # if no $name, then it's the prologue -- discard
  202.         if ($fn) { print FILE substr($buf, 0, $bpos-2); }
  203.         else     { $in {$name} .= substr($buf, 0, $bpos-2); } # kill last \r\n
  204.       }
  205.       close (FILE);
  206.       last PART if substr($buf, $bpos + $blen, 4) eq "--\r\n";
  207.       substr($buf, 0, $bpos+$blen+2) = '';
  208.       $amt = ($left > $bufsize+$maxbound-length($buf) 
  209.           ? $bufsize+$maxbound-length($buf) : $left);
  210.       $errflag = (($got = read(STDIN, $buf, $amt, length($buf))) != $amt);
  211.       die "Short Read: wanted $amt, got $got\n" if $errflag;
  212.       $left -= $amt;
  213.  
  214.  
  215.       undef $head;  undef $fn;
  216.      HEAD:
  217.       while (($lpos = index($buf, "\r\n\r\n")) == -1) { 
  218.         die $@ if $errflag;
  219.         $head .= substr($buf, 0, $bufsize);
  220.         $buf = substr($buf, $bufsize);
  221.         $amt = ($left > $bufsize ? $bufsize : $left); #$maxbound==length($buf);
  222.         $errflag = (($got = read(STDIN, $buf, $amt, $maxbound)) != $amt);  
  223.         die "Short Read: wanted $amt, got $got\n" if $errflag;
  224.         $left -= $amt;
  225.       }
  226.       $head .= substr($buf, 0, $lpos+2);
  227.       push (@in, $head);
  228.       @heads = split("\r\n", $head);
  229.       ($cd) = grep (/^\s*Content-Disposition:/i, @heads);
  230.       ($ct) = grep (/^\s*Content-Type:/i, @heads);
  231.  
  232.       ($name) = $cd =~ /\bname="([^"]+)"/i; #"; 
  233.       ($name) = $cd =~ /\bname=([^\s:;]+)/i unless defined $name;  
  234.  
  235.       ($fname) = $cd =~ /\bfilename="([^"]*)"/i; #"; # filename can be null-str
  236.       ($fname) = $cd =~ /\bfilename=([^\s:;]+)/i unless defined $fname;
  237.       $incfn{$name} .= (defined $in{$name} ? "\0" : "") . 
  238.         (defined $fname ? $fname : "");
  239.  
  240.       ($ctype) = $ct =~ /^\s*Content-type:\s*"([^"]+)"/i;  #";
  241.       ($ctype) = $ct =~ /^\s*Content-Type:\s*([^\s:;]+)/i unless defined $ctype;
  242.       $inct{$name} .= (defined $in{$name} ? "\0" : "") . $ctype;
  243.  
  244.       if ($writefiles && defined $fname) {
  245.         $ser++;
  246.     $fn = $writefiles . ".$$.$ser";
  247.     open (FILE, ">$fn") || &CgiDie("Couldn't open $fn\n");
  248.         binmode (FILE);  # write files accurately
  249.       }
  250.       substr($buf, 0, $lpos+4) = '';
  251.       undef $fname;
  252.       undef $ctype;
  253.     }
  254.  
  255. 1;
  256. END_MULTIPART
  257.     if ($errflag) {
  258.       local ($errmsg, $value);
  259.       $errmsg = $@ || $errflag;
  260.       foreach $value (values %insfn) {
  261.         unlink(split("\0",$value));
  262.       }
  263.       &CgiDie($errmsg);
  264.     } else {
  265.       # everything's ok.
  266.     }
  267.   } else {
  268.     &CgiDie("cgi-lib.pl: Unknown Content-type: $ENV{'CONTENT_TYPE'}\n");
  269.   }
  270.  
  271.   # no-ops to avoid warnings
  272.   $insfn = $insfn;
  273.   $incfn = $incfn;
  274.   $inct  = $inct;
  275.  
  276.   $^W = $perlwarn;
  277.  
  278.   return ($errflag ? undef :  scalar(@in)); 
  279. }
  280.  
  281.  
  282. # PrintHeader
  283. # Returns the magic line which tells WWW that we're an HTML document
  284.  
  285. sub PrintHeader {
  286.   return "Content-type: text/html\n\n";
  287. }
  288.  
  289.  
  290. # HtmlTop
  291. # Returns the <head> of a document and the beginning of the body
  292. # with the title and a body <h1> header as specified by the parameter
  293.  
  294. sub HtmlTop
  295. {
  296.   local ($title) = @_;
  297.  
  298.   return <<END_OF_TEXT;
  299. <html>
  300. <head>
  301. <title>$title</title>
  302. </head>
  303. <body>
  304. <h1>$title</h1>
  305. END_OF_TEXT
  306. }
  307.  
  308.  
  309. # HtmlBot
  310. # Returns the </body>, </html> codes for the bottom of every HTML page
  311.  
  312. sub HtmlBot
  313. {
  314.   return "</body>\n</html>\n";
  315. }
  316.  
  317.  
  318. # SplitParam
  319. # Splits a multi-valued parameter into a list of the constituent parameters
  320.  
  321. sub SplitParam
  322. {
  323.   local ($param) = @_;
  324.   local (@params) = split ("\0", $param);
  325.   return (wantarray ? @params : $params[0]);
  326. }
  327.  
  328.  
  329. # MethGet
  330. # Return true if this cgi call was using the GET request, false otherwise
  331.  
  332. sub MethGet {
  333.   return (defined $ENV{'REQUEST_METHOD'} && $ENV{'REQUEST_METHOD'} eq "GET");
  334. }
  335.  
  336.  
  337. # MethPost
  338. # Return true if this cgi call was using the POST request, false otherwise
  339.  
  340. sub MethPost {
  341.   return (defined $ENV{'REQUEST_METHOD'} && $ENV{'REQUEST_METHOD'} eq "POST");
  342. }
  343.  
  344.  
  345. # MyBaseUrl
  346. # Returns the base URL to the script (i.e., no extra path or query string)
  347. sub MyBaseUrl {
  348.   local ($ret, $perlwarn);
  349.   $perlwarn = $^W; $^W = 0;
  350.   $ret = 'http://' . $ENV{'SERVER_NAME'} .  
  351.          ($ENV{'SERVER_PORT'} != 80 ? ":$ENV{'SERVER_PORT'}" : '') .
  352.          $ENV{'SCRIPT_NAME'};
  353.   $^W = $perlwarn;
  354.   return $ret;
  355. }
  356.  
  357.  
  358. # MyFullUrl
  359. # Returns the full URL to the script (i.e., with extra path or query string)
  360. sub MyFullUrl {
  361.   local ($ret, $perlwarn);
  362.   $perlwarn = $^W; $^W = 0;
  363.   $ret = 'http://' . $ENV{'SERVER_NAME'} .  
  364.          ($ENV{'SERVER_PORT'} != 80 ? ":$ENV{'SERVER_PORT'}" : '') .
  365.          $ENV{'SCRIPT_NAME'} . $ENV{'PATH_INFO'} .
  366.          (length ($ENV{'QUERY_STRING'}) ? "?$ENV{'QUERY_STRING'}" : '');
  367.   $^W = $perlwarn;
  368.   return $ret;
  369. }
  370.  
  371.  
  372. # MyURL
  373. # Returns the base URL to the script (i.e., no extra path or query string)
  374. # This is obsolete and will be removed in later versions
  375. sub MyURL  {
  376.   return &MyBaseUrl;
  377. }
  378.  
  379.  
  380. # CgiError
  381. # Prints out an error message which which containes appropriate headers,
  382. # markup, etcetera.
  383. # Parameters:
  384. #  If no parameters, gives a generic error message
  385. #  Otherwise, the first parameter will be the title and the rest will 
  386. #  be given as different paragraphs of the body
  387.  
  388. sub CgiError {
  389.   local (@msg) = @_;
  390.   local ($i,$name);
  391.  
  392.   if (!@msg) {
  393.     $name = &MyFullUrl;
  394.     @msg = ("Error: script $name encountered fatal error\n");
  395.   };
  396.  
  397.   if (!$cgi_lib'headerout) { #')
  398.     print &PrintHeader;    
  399.     print "<html>\n<head>\n<title>$msg[0]</title>\n</head>\n<body>\n";
  400.   }
  401.   print "<h1>$msg[0]</h1>\n";
  402.   foreach $i (1 .. $#msg) {
  403.     print "<p>$msg[$i]</p>\n";
  404.   }
  405.  
  406.   $cgi_lib'headerout++;
  407. }
  408.  
  409.  
  410. # CgiDie
  411. # Identical to CgiError, but also quits with the passed error message.
  412.  
  413. sub CgiDie {
  414.   local (@msg) = @_;
  415.   &CgiError (@msg);
  416.   die @msg;
  417. }
  418.  
  419.  
  420. # PrintVariables
  421. # Nicely formats variables.  Three calling options:
  422. # A non-null associative array - prints the items in that array
  423. # A type-glob - prints the items in the associated assoc array
  424. # nothing - defaults to use %in
  425. # Typical use: &PrintVariables()
  426.  
  427. sub PrintVariables {
  428.   local (*in) = @_ if @_ == 1;
  429.   local (%in) = @_ if @_ > 1;
  430.   local ($out, $key, $output);
  431.  
  432.   $output =  "\n<dl compact>\n";
  433.   foreach $key (sort keys(%in)) {
  434.     foreach (split("\0", $in{$key})) {
  435.       ($out = $_) =~ s/\n/<br>\n/g;
  436.       $output .=  "<dt><b>$key</b>\n <dd>:<i>$out</i>:<br>\n";
  437.     }
  438.   }
  439.   $output .=  "</dl>\n";
  440.  
  441.   return $output;
  442. }
  443.  
  444. # PrintEnv
  445. # Nicely formats all environment variables and returns HTML string
  446. sub PrintEnv {
  447.   &PrintVariables(*ENV);
  448. }
  449.  
  450.  
  451. # The following lines exist only to avoid warning messages
  452. $cgi_lib'writefiles =  $cgi_lib'writefiles;
  453. $cgi_lib'bufsize    =  $cgi_lib'bufsize ;
  454. $cgi_lib'maxbound   =  $cgi_lib'maxbound;
  455. $cgi_lib'version    =  $cgi_lib'version;
  456. $cgi_lib'filepre    =  $cgi_lib'filepre;
  457.  
  458. 1; #return true 
  459.  
  460.